var application = require('application');
var appUtil = require("utils/utils");

var REQUEST_REQUIRED_PERMISSIONS = 1234;

var checkPermission = function() {
    if (android.support.v4.content.ContextCompat.checkSelfPermission(application.android.currentContext, android.Manifest.permission.ACCESS_FINE_LOCATION) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
        android.support.v4.app.ActivityCompat.requestPermissions(application.android.currentContext, [android.Manifest.permission.ACCESS_FINE_LOCATION], REQUEST_REQUIRED_PERMISSIONS);
        return false;
    } else {
        return true;
    }
}

var getPosition = function () {
    
    return new Promise(function (resolve, reject) {
        try {
            if (!checkPermission()) {
                reject(new Error("permission denied"));
            }
            var client = new com.baidu.location.LocationClient (appUtil.ad.getApplicationContext());
            var options = new com.baidu.location.LocationClientOption ();
            options.setLocationMode(com.baidu.location.LocationClientOption.LocationMode.Hight_Accuracy); // 高精度定位
            options.setCoorType("bd09ll");
            options.setOpenGps(true);
        //        locationClientOption.set;
            // 返回地址信息
            options.setIsNeedAddress(true);
            options.setEnableSimulateGps(true);
        //        设置刷新间隔，这里只需要定位一次所以不需要
        //        locationClientOption.setScanSpan(3 * 1000);
            options.setTimeOut(5 * 1000);
            options.setIsNeedLocationDescribe(true);
            client.setLocOption(options);
            // client.start();
            console.log("lbsBaidu version " + client.getVersion());
            console.log("set BDLocationListener");

            client.registerLocationListener(new com.baidu.location.BDLocationListener({
                onReceiveLocation: function (bdLocation) {
                    console.log("resolve bdLocation");
                    // console.log(bdLocation.getAddrStr());
                    // console.dump(bdLocation.getAddrStr());
                    var res = {
                        addr: bdLocation.getAddrStr(),
                        locType: bdLocation.getLocType(),
                        latitude: bdLocation.getLatitude(),
                        longitude: bdLocation.getLongitude(),
                        radius: bdLocation.getRadius(),
                    }
                    resolve(res);
                }
            }));
            client.start();
        } catch (e) {
            console.log("catch error, stop lbs client");
            // client.stop();
            if (reject) {
                reject(e);
            }
            reject(e);
        }
    })
}

exports.getPosition = getPosition;
